"use client"

import { useState, useEffect } from 'react'
import { textStyles } from '../../../lib/fontConfig'

interface MemoryCardGameProps {
  targetChar: string
  onGameEnd: (score: number, correct: number, total: number) => void
}

interface Card {
  id: number
  content: string
  type: 'character' | 'meaning'
  isFlipped: boolean
  isMatched: boolean
  pairId: number
}

export function MemoryCardGame({ targetChar, onGameEnd }: MemoryCardGameProps) {
  const [cards, setCards] = useState<Card[]>([])
  const [flippedCards, setFlippedCards] = useState<number[]>([])
  const [matchedPairs, setMatchedPairs] = useState<number[]>([])
  const [score, setScore] = useState(0)
  const [timeLeft, setTimeLeft] = useState(60)
  const [level, setLevel] = useState(1)
  const [gameStarted, setGameStarted] = useState(false)

  // 初始化卡片
  useEffect(() => {
    const cardPairs = [
      { character: '木', meaning: '树木' },
      { character: '人', meaning: '人类' },
      { character: '水', meaning: '水流' },
      { character: '火', meaning: '火焰' },
      { character: '土', meaning: '土地' },
      { character: '山', meaning: '山峰' },
      { character: '石', meaning: '石头' },
      { character: '日', meaning: '太阳' }
    ]

    const gameCards: Card[] = []
    cardPairs.forEach((pair, index) => {
      gameCards.push({
        id: index * 2,
        content: pair.character,
        type: 'character',
        isFlipped: false,
        isMatched: false,
        pairId: index
      })
      gameCards.push({
        id: index * 2 + 1,
        content: pair.meaning,
        type: 'meaning',
        isFlipped: false,
        isMatched: false,
        pairId: index
      })
    })

    // 打乱卡片顺序
    const shuffledCards = gameCards.sort(() => Math.random() - 0.5)
    setCards(shuffledCards)
  }, [])

  // 计时器
  useEffect(() => {
    if (gameStarted && timeLeft > 0) {
      const timer = setTimeout(() => {
        setTimeLeft(prev => prev - 1)
      }, 1000)
      return () => clearTimeout(timer)
    } else if (timeLeft === 0) {
      onGameEnd(score, matchedPairs.length, 8)
    }
  }, [timeLeft, gameStarted, score, matchedPairs.length, onGameEnd])

  // 处理卡片点击
  const handleCardClick = (cardId: number) => {
    if (!gameStarted) setGameStarted(true)
    
    const card = cards.find(c => c.id === cardId)
    if (!card || card.isFlipped || card.isMatched || flippedCards.length >= 2) return

    const newFlippedCards = [...flippedCards, cardId]
    setFlippedCards(newFlippedCards)

    // 更新卡片状态
    setCards(prev => prev.map(c => 
      c.id === cardId ? { ...c, isFlipped: true } : c
    ))

    // 检查配对
    if (newFlippedCards.length === 2) {
      const [firstId, secondId] = newFlippedCards
      const firstCard = cards.find(c => c.id === firstId)
      const secondCard = cards.find(c => c.id === secondId)

      setTimeout(() => {
        if (firstCard && secondCard && firstCard.pairId === secondCard.pairId) {
          // 配对成功
          setMatchedPairs(prev => [...prev, firstCard.pairId])
          setScore(prev => prev + 100)
          setCards(prev => prev.map(c => 
            c.pairId === firstCard.pairId ? { ...c, isMatched: true } : c
          ))
          
          // 检查游戏是否完成
          if (matchedPairs.length + 1 === 8) {
            setTimeout(() => {
              onGameEnd(score + 100, matchedPairs.length + 1, 8)
            }, 500)
          }
        } else {
          // 配对失败，翻回去
          setCards(prev => prev.map(c => 
            newFlippedCards.includes(c.id) ? { ...c, isFlipped: false } : c
          ))
        }
        setFlippedCards([])
      }, 1000)
    }
  }

  const resetGame = () => {
    setFlippedCards([])
    setMatchedPairs([])
    setScore(0)
    setTimeLeft(60)
    setGameStarted(false)
    setCards(prev => prev.map(c => ({ ...c, isFlipped: false, isMatched: false })))
  }

  return (
    <div className="h-full flex flex-col bg-white rounded-2xl p-6 relative">
      {/* 游戏标题和关闭按钮 */}
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center space-x-3">
          <div className="w-8 h-8 bg-pink-500 rounded-lg flex items-center justify-center">
            <span className="text-white text-lg">🧠</span>
          </div>
          <h3 className="text-xl font-bold text-gray-800">字根记忆翻牌</h3>
        </div>
        <button
          onClick={() => onGameEnd(score, matchedPairs.length, 8)}
          className="w-8 h-8 bg-red-500 rounded-full flex items-center justify-center text-white hover:bg-red-600 transition-colors"
        >
          ✕
        </button>
      </div>

      {/* 游戏状态栏 */}
      <div className="grid grid-cols-3 gap-4 mb-6">
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{score}</div>
          <div className="text-sm text-gray-600">得分</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">
            {Math.floor(timeLeft / 60).toString().padStart(2, '0')}:
            {(timeLeft % 60).toString().padStart(2, '0')}
          </div>
          <div className="text-sm text-gray-600">时间</div>
        </div>
        <div className="text-center">
          <div className="text-2xl font-bold text-gray-800">{level}</div>
          <div className="text-sm text-gray-600">关卡</div>
        </div>
      </div>
      
      {/* 游戏区域 */}
      <div className="flex-1 flex items-center justify-center">
        <div className="grid grid-cols-4 gap-4 max-w-lg">
          {cards.map((card) => (
            <div
              key={card.id}
              onClick={() => handleCardClick(card.id)}
              className={`
                w-20 h-20 rounded-xl flex items-center justify-center cursor-pointer
                transition-all duration-300 transform hover:scale-105 shadow-lg
                ${card.isFlipped || card.isMatched
                  ? 'bg-gradient-to-br from-blue-400 to-blue-500 text-white'
                  : 'bg-gradient-to-br from-purple-400 to-purple-500 hover:from-purple-500 hover:to-purple-600 text-white'
                }
                ${card.isMatched ? 'opacity-50 scale-95' : ''}
              `}
            >
              {card.isFlipped || card.isMatched ? (
                <span className="text-sm font-bold text-white text-center px-1">
                  {card.content}
                </span>
              ) : (
                <span className="text-2xl text-white">❓</span>
              )}
            </div>
          ))}
        </div>
      </div>

      {/* 底部控制按钮 */}
      <div className="flex justify-center space-x-4 mt-6">
        <button 
          onClick={() => setGameStarted(!gameStarted)}
          className="px-6 py-2 bg-blue-500 text-white rounded-full hover:bg-blue-600 transition-colors flex items-center space-x-2"
        >
          <span>{gameStarted ? '⏸️' : '▶️'}</span>
          <span>{gameStarted ? '暂停' : '开始'}</span>
        </button>
        <button 
          onClick={resetGame}
          className="px-6 py-2 bg-orange-500 text-white rounded-full hover:bg-orange-600 transition-colors flex items-center space-x-2"
        >
          <span>🔄</span>
          <span>重新开始</span>
        </button>
        <button className="px-6 py-2 bg-green-500 text-white rounded-full hover:bg-green-600 transition-colors flex items-center space-x-2">
          <span>⏭️</span>
          <span>下一关</span>
        </button>
        <button 
          onClick={() => onGameEnd(score, matchedPairs.length, 8)}
          className="px-6 py-2 bg-gray-500 text-white rounded-full hover:bg-gray-600 transition-colors flex items-center space-x-2"
        >
          <span>🚪</span>
          <span>退出游戏</span>
        </button>
      </div>
    </div>
  )
} 